import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 循环屏障
 */
public class CyclicBarrierDemo1 {
    public static void main(String[] args) {
      //循环屏障
        CyclicBarrier cyclicBarrier=new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println("计数器为0了");
            }
        });
        ExecutorService service= Executors.newFixedThreadPool(10);
        for (int i = 0; i <10 ; i++) {
            int finalI = i;
            service.submit(()->{
                Thread currThread=Thread.currentThread();
                System.out.println("执行线程:"+currThread.getName());
                try {
                    Thread.sleep(500* finalI);
                    cyclicBarrier.await();//执行阻塞等待，直到循环屏障计数器为0
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println("线程执行完成"+currThread.getName());
            });
        }
    }
}
